<template>
  <div>
    <CategorySelector :disabledSelector="isShowAttrList" style="margin-bottom: 50px" @category3ID="categoryIDChange"/>
    <el-card class="box-card">
      <div v-if="isShowAttrList">
            <el-button
              type="primary"
              class="button"
              :icon="Plus"
              :disabled="!category3Id.value"
              @click="addAttr"
            >
              添加属性
            </el-button>
        <el-table border style="width: 100%" :data="attrList">
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="100%"
          />
          <el-table-column
            prop="attrName"
            label="属性值名称"
            align="center"
            width="300"
          />
          <el-table-column
            prop=""
            label="属性值列表"
            align="center"
            width="300"
          >
            <template v-slot="{ row }">
              <el-tag
                class="ml-2"
                style="margin-right: 6px"
                type="success"
                v-for="attrValue in row.attrValueList"
                :key="attrValue.id"
                >{{ attrValue.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="address" align="center" label="操作">
            <template v-slot="{ row }">
              <el-button
                type="warning"
                size="small"
                class="button"
                title="修改"
                :icon="Edit"
                @click="editAttr(row)"
                >编辑</el-button
              >

              <el-popconfirm
                title="确定要删除此条属性吗?"
                @confirm="confirmEvent(row.id)"
              >
                <template #reference>
                  <el-button
                    type="success"
                    size="small"
                    class="button"
                    :icon="Delete"
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="属性名">
            <el-input v-model="attrInfo.attrName" placeholder="请输入属性名" />
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          @click="addAttrValue"
          :disabled="!attrInfo.attrName"
          >添加属性值</el-button
        >
        <el-table :data="attrInfo.attrValueList" style="margin: 10px">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          />
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <el-input
                ref="inputRef"
                v-if="row.isShowInput"
                size="small"
                v-model="row.valueName"
                placeholder="请输入属性值"
                @blur="deleteCurrentRow(row, $index)"
              ></el-input>
              <span
                v-else
                @dblclick="toEditCurrentRow(row, $index)"
                style="display: inline-block; width: 80%"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-popconfirm
                title="确定要删除此条属性值吗?"
                @confirm="deleteAttrInfo($index)"
              >
                <template #reference>
                  <el-button
                    :icon="Delete"
                    type="danger"
                    size="small"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          :disabled="!attrInfo.attrValueList.length"
          @click="toAddOrUpdateAttr(

          )"
          >保存</el-button
        >
        <el-button type="default" @click="isShowAttrList = true"
          >取消</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import CategorySelector from "@/components/CategorySelector/index.vue";
export default {
  name: "Attr",
  components: { CategorySelector },
};
</script>
<script lang="ts" setup>
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
import { ref, watch, reactive, nextTick } from "vue";
import {
  reqGetAttrListDataByCategory3Id,
  reqDeleteOneAttr,
  reqEditAttrList,
} from "@/api/product/attr";
import type {
  AttrListModel,
  AttrValueInfoModel,
  AttrInfoModel,
} from "@/api/product/model/attrModel";
import { ElMessage } from "element-plus";
let category1Id = ref<any>("");
let category2Id = ref<any>("");
let category3Id = ref<any>("");
const categoryIDChange = (n: any) => {
  // category3ID.value = n.value
  category1Id.value = n.category1Id;
  category2Id.value = n.category2Id;
  category3Id.value = n.category3Id;

  console.log("[HMZ]", n);
  console.log("[HMZ]", category1Id, category2Id, category3Id);
};
const isShowAttrList = ref<boolean>(true);
const attrList = ref<AttrListModel>([]);
const inputRef = ref();
//获取属性列表
const getAttrListData = async () => {
  attrList.value = await reqGetAttrListDataByCategory3Id({
    category1ID: category1Id.value.value,
    category2ID: category2Id.value.value,
    category3ID: category3Id.value.value,
  });
};
// 定义一个存储添加属性时的对象
const attrInfo = reactive<AttrInfoModel>({
  attrName: "", // 待添加的属性名
  attrValueList: [], // 属性名对应的那些具体的属性值
  categoryId: -1, // 三级分类的具体的id
  categoryLevel: 3, // 几级分类 当前添加的只有一个三级分类 所以写3即可
});
//删除属性接口
const confirmEvent = async (id: any) => {
  await reqDeleteOneAttr(id);
  //提示一下删除成功
  ElMessage.success("删除属性成功...");
  //成功之后重新发送请求获取数据
  getAttrListData();
};
//根据三级导航ID来获取属性列表 需要监听三级导航id得变化
watch(
  () => category3Id.value.value,
  (newVal: any) => {
    if (!newVal) {
      attrList.value = [];
      return;
    }
    //触发三级id值后发送请求
    getAttrListData(); // 获取属性列表
  },
  { immediate: true }
);
//ref监听方式


//添加属性
const addAttr = () => {
  isShowAttrList.value = false;
  attrInfo.attrName = "";
  attrInfo.attrValueList = [];

  //删除更新操作时得ID
  delete attrInfo.id;
};

//编辑属性
const editAttr = (row: AttrListModel) => {
  isShowAttrList.value = false;
  Object.assign(attrInfo, row);
};

// const editAttr = async (id:number) => {
//   await reqEditAttrList(id)
// };

//删除属性的某一个值
const deleteAttrInfo = (index: number) => {
  attrInfo.attrValueList.splice(index, 1);
};
// 3. 实现属性值的添加 也就是将属性值追加到attrValueList当中
const addAttrValue = () => {
  attrInfo.attrValueList.push({
    valueName: "",
    isShowInput: true,
  });

  // 上面数据添加了之后，因为数据是响应式的原因，页面中需要实现渲染 而页面数据的渲染是异步的
  nextTick(() => {
    inputRef.value?.focus();
    // console.log('attrInput',inputRef)
  });
};

// 4. 失去焦点时 如果属性值输入框中无值时 要删除当前行 否则要显示p标签
const deleteCurrentRow = (row: AttrValueInfoModel, index: number) => {
  const item = attrInfo.attrValueList
    .slice(0, -1)
    .find((item) => item.valueName === row.valueName);
  // 如果当前新增加属性值与之前重复 则要删除掉
  // 另外一个row.id 表示判断当前操作是不是更新
  if (!row.valueName || (item && !row.id)) {
    attrInfo.attrValueList.splice(index, 1);
    return;
  }

  // 如果当前行的输入框中有值 则要显示p标签 隐藏input标签
  row.isShowInput = false;
};

// 5. 编辑属性值
const toEditCurrentRow = (row: AttrValueInfoModel, $index: number) => {
  // 5.1 只需要切换回输入框
  row.isShowInput = true;

  // 并且要让当前行还是有一个获得焦点的效果
  nextTick(() => {
    inputRef.value?.focus();
  });
};
//添加或更新属性值
const toAddOrUpdateAttr = async()=>{
  // attrInfo.categoryId = category3Id.
  console.log(category3Id);
  console.log("Hmz",attrInfo.categoryId.value);
  // console.log(attrInfo.Target);
  await reqEditAttrList(attrInfo);
  //提示添加信息成功
  ElMessage.success('添加属性成功😊😊😊')
  //跳转到属性列表页面
  isShowAttrList.value = true
  //重新获取一下数据
  getAttrListData()
}
</script>

<style></style>
